using System.Collections.Generic;
using System.Windows.Forms;

namespace Schedulr.Helpers
{
    /// <summary>
    /// Contains helper methods for working with grids.
    /// </summary>
    internal static class GridHelper
    {
        /// <summary>
        /// Gets the selected rows.
        /// </summary>
        /// <param name="reverse">Determines if the rows should be returned in reverse order.</param>
        /// <returns>The currently selected rows.</returns>
        public static IList<DataGridViewRow> GetSelectedRows(DataGridView grid, bool reverse)
        {
            List<DataGridViewRow> selectedRows = new List<DataGridViewRow>();
            foreach (DataGridViewCell cell in grid.SelectedCells)
            {
                if (cell.OwningRow.DataBoundItem != null && !selectedRows.Contains(cell.OwningRow))
                {
                    selectedRows.Add(cell.OwningRow);
                }
            }
            if (reverse)
            {
                selectedRows.Reverse();
            }

            return selectedRows;
        }

        public static IList<TDataBoundItemType> GetSelectedItems<TDataBoundItemType>(DataGridView grid)
        {
            List<TDataBoundItemType> selectedItems = new List<TDataBoundItemType>();
            foreach (DataGridViewRow selectedRow in GridHelper.GetSelectedRows(grid, false))
            {
                TDataBoundItemType selectedItem = (TDataBoundItemType)selectedRow.DataBoundItem;
                selectedItems.Add(selectedItem);
            }
            return selectedItems;
        }
    }
}